package com.sendi.system.action;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.sendi.system.entity.SystemPower;
import com.sendi.system.entity.User;
import com.sendi.system.entity.UserRole;
import com.sendi.system.entity.UserRoleRelation;
/*
 * 角度管理增加修改，删除查询
 * 并关联用户
 */
public class UserroleAction extends SysAction {
    private Integer  id;
    
	private String rolename;
	private String roledesc;
	private String loginip;
	private String area;
	private String isvalidataip="off";
	
   private String deleterecord;
   private String querytype;
   
   private Integer useroleid;
  
   private String username;
   
   private String itemselector;
   
	public UserroleAction()
	{
		super();
		data_session_name="UserroleActionListData";
	}
	
	
	public void userroleInit()
	{
		List datas=null;
		
		if(getSession().getAttribute(data_session_name)!=null)
		{
			datas=(List)getSession().getAttribute(data_session_name);
			System.out.println("use session size"+datas.size());
		}
		else
		{
			addUserroleTosessin();
			datas=(List)getSession().getAttribute(data_session_name);
		}
		 
			writeJSONArray(datas);
		 
	}
	
	public void addUserroleTosessin()
	{
		List datas=null;
		String hql="from  UserRole";
		 
		datas=serviceSupportImp.findByHQL(hql);
	 
		for(Object o:datas)
		{
			UserRole user=(UserRole) o;
		  	
		}
		getSession().setAttribute(data_session_name,datas);
	 	System.out.println("data size:"+datas.size());
	}
	
 
   /*
    * 查询用户
    */
	public void queryUserrole()
	{
		   try
		   {   
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from UserRole where 1=1 ");
				if(rolename!=null&&rolename.trim().length()>0)
				{
					hql.append(" and  rolename like :rolename ");
				}
				 
				   Query query= session.createQuery(hql.toString());
				   if(rolename!=null&&rolename.trim().length()>0)
					{
					  query.setParameter("rolename", "%"+rolename+"%");
					}
				 	    List datas=query.list();
					    System.out.println("query size"+datas.size());
				     	getSession().setAttribute(data_session_name,datas);	
				     	writeResponseText("{success:true,msg:'success',datasize:"+datas.size()+"}");
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}

 
	 public void addUserrole()
	 {
		 
		 	 UserRole userRole=new UserRole();
		 	userRole.setArea(area);
		 	userRole.setIsvalidataip(isvalidataip);
		 	userRole.setLoginip(loginip);
		 	userRole.setRolename(rolename);
		 	userRole.setRoledesc(roledesc);
			
			try {
				serviceSupportImp.save(userRole);
				getSession().removeAttribute(data_session_name);
				addUserroleTosessin();
				writeResponseText("{success:true,msg:'success'}");
		 	} catch (Exception e) {
				writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			  e.printStackTrace();
			}
	 }

	 
	 public void excutModifyQueryuserrole()
		{
			String hql="from UserRole where 1=1 and id="+this.id; 
		 	List datas=serviceSupportImp.findByHQL(hql);
		  	UserRole userRole=(UserRole)datas.get(0);
			try {
				getResponse().setCharacterEncoding("UTF-8"); //编码为UTF-8否则乱码
				getResponse().getWriter().write("{success:true,datas:"+JSONObject.fromObject(userRole).toString()+"}");
			} catch (IOException e) {
				try {
					getResponse().getWriter().write("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
				} catch (IOException e1) {
				 
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
			
		}
		public void excuteModifyuserrole()
		{
		 
			String hql="from UserRole where 1=1 and id="+this.id; 
		 	List datas=serviceSupportImp.findByHQL(hql);
		  	UserRole userRole=(UserRole)datas.get(0);
		 	userRole.setArea(area);
		 	userRole.setIsvalidataip(isvalidataip);
		 	userRole.setLoginip(loginip);
		 	userRole.setRolename(rolename);
		 	userRole.setRoledesc(roledesc);
		  	serviceSupportImp.update(userRole);
		 	getSession().removeAttribute(data_session_name);
			addUserroleTosessin();
			writeResponseText("{success:true,msg:'success'}"); 
		}
		
		public void excuteDeleteuserrole()
		{
		  String hql="delete from user_role where id in ("+deleterecord+")";
		  String hql2="delete from system_power where  roleid in  ("+deleterecord+")";
		    String sql[]=new String[2];
		     sql[0]=hql;
		     sql[1]=hql2;
		   this.excuteBatchDelete(sql);
		   addUserroleTosessin();
		   writeResponseText("{success:true,msg:'success'}"); 
		   reloadSysPower();
		    
	 	}
		public void reloadSysPower()
		{
			 	  ///重新加载内存中的权限信息
				     String hql7="from SystemPower";
			 	     HashMap<String,SystemPower> systemPower=(HashMap<String,SystemPower>)applicationContextHelper.servletContext.getAttribute("sendi_sys_moudlePower_info");;
			 	     systemPower.clear();
			 	     List datas7=this.getListData(hql7);
					 for(Object o7:datas7)
					 {
						 SystemPower slb=(SystemPower)o7;
						 systemPower.put(slb.getId()+"",slb);
					 }
	 		  
	 	}
		/*
		 * 查询该角色所有已选择与其他还没有选择的用户
		 */
		public void QuerySelAndUnSelUser()
		{
			 if(this.querytype.equals("querynoselectuser")) //查询还没有选择的用户
			 {
				   String sql="SELECT   sys_user.userName,  sys_user.id  FROM   sys_user where  sys_user.id NOT IN (SELECT user_role_relation.userid FROM user_role_relation WHERE user_role_relation.roleid ="+this.useroleid+") ";
			       if(this.username!=null&&this.username.trim().length()>0)
			       {
			    	   sql+=" and user.userName like '%"+this.username+"%' ";
			       }
			       
			     Session session=this.serviceSupportImp.getDao().getSessionFactory().openSession();
			  
			    List<com.sendi.system.bean.User> returelist=new ArrayList<com.sendi.system.bean.User>();
			    List querylist= session.createSQLQuery(sql).addScalar("userName",Hibernate.STRING).addScalar("id",Hibernate.INTEGER).list();
			   for(Object o:querylist)
			   {
				    Object oarr[]=(Object [])o;
				    com.sendi.system.bean.User u=new com.sendi.system.bean.User();
				    u.setUsername(oarr[0].toString());
				    u.setUserid(Integer.parseInt(oarr[1].toString()));
			 	    returelist.add(u);
			   }
		 	   writeJSONArray(returelist);
		 	       
			 }
			 else
			 {
				   String sql="SELECT   sys_user.userName,  sys_user.id  FROM   sys_user where  sys_user.id    IN (SELECT user_role_relation.userid FROM user_role_relation WHERE user_role_relation.roleid ="+this.useroleid+") ";
				      
			     Session session=this.serviceSupportImp.getDao().getSessionFactory().openSession();
			  
			    List<com.sendi.system.bean.User> returelist=new ArrayList<com.sendi.system.bean.User>();
			    List querylist= session.createSQLQuery(sql).addScalar("userName",Hibernate.STRING).addScalar("id",Hibernate.INTEGER).list();
			    System.out.println("sql query list2 "+querylist.size()); 
			   for(Object o:querylist)
			   {
				    Object oarr[]=(Object [])o;
				    com.sendi.system.bean.User u=new com.sendi.system.bean.User();
				    u.setUsername(oarr[0].toString());
				    u.setUserid(Integer.parseInt(oarr[1].toString()));
			 	    returelist.add(u);
			   }
		 	   writeJSONArray(returelist);
		 	 }
			
		}
	  /*
	   * 需要将用户组关系删除，然后再进行重新插入
	   */
		public void addUserToUserrole()
		{
			 String sql="delete from user_role_relation  WHERE user_role_relation.roleid ="+this.useroleid;
			 Connection con=this.getConnection();
			 Statement state;
			try {
				state = con.createStatement();
				state.executeUpdate(sql);
			 	String sql2="insert into user_role_relation (roleid,userid) values (?,?)";
			 	if(this.itemselector!=null&&this.itemselector.trim().length()>0)
			 	{
			 		String a[]=this.itemselector.split(",");
			 	 PreparedStatement psd=con.prepareStatement(sql2);
			 		for(String b:a)
				 	{
				 		
				 		psd.setInt(1,this.useroleid);
				 		psd.setInt(2,Integer.parseInt(b));
				 		psd.addBatch();
				 	}
			 		psd.executeBatch();
			  	}
			 	
			 	
				
			} catch (SQLException e) {
				 
				e.printStackTrace();
			}
			finally
			{
				try {
					con.close();
				} catch (SQLException e) {
				 
					e.printStackTrace();
				}
			}
		  	 
 			 writeResponseText("{success:true,msg:'success'}"); 
 			reloadUserroleRelation();
 			
		}
		/*
		 * 重新加载角色信息
		 * 其实这种角色信息的更新并没有对数据并发进行保护，所以在并发量太高时，可能会出现问题，
		 * 但考虑到一旦系统投入使用，这种信息基本上都是确定的，所以没有做这种保护代码 
		 */
		public void reloadUserroleRelation()
		{
			 		HashMap<String,UserRoleRelation> userRoleRelation=(HashMap<String,UserRoleRelation>)applicationContextHelper.servletContext.getAttribute("sendi_sys_userRoleRelation_info");
			 		userRoleRelation.clear();
			 		String hql6="from UserRoleRelation";
					 List datas6=this.getListData(hql6);
					 for(Object o6:datas6)
					 {
						 UserRoleRelation slb=(UserRoleRelation)o6;
						 userRoleRelation.put(slb.getId()+"",slb);
					 }
				 
 		}

	public Integer getId() {
		return id;
	}



	public void setId(Integer id) {
		this.id = id;
	}

 


	public String getDeleterecord() {
		return deleterecord;
	}


	public void setDeleterecord(String deleterecord) {
		this.deleterecord = deleterecord;
	}


	public String getRolename() {
		return rolename;
	}


	public void setRolename(String rolename) {
		this.rolename = rolename;
	}


	public String getRoledesc() {
		return roledesc;
	}


	public void setRoledesc(String roledesc) {
		this.roledesc = roledesc;
	}


	public String getLoginip() {
		return loginip;
	}


	public void setLoginip(String loginip) {
		this.loginip = loginip;
	}


	public String getArea() {
		return area;
	}


	public void setArea(String area) {
		this.area = area;
	}


	public String getIsvalidataip() {
		return isvalidataip;
	}


	public void setIsvalidataip(String isvalidataip) {
		this.isvalidataip = isvalidataip;
	}


	public String getQuerytype() {
		return querytype;
	}


	public void setQuerytype(String querytype) {
		this.querytype = querytype;
	}


	public Integer getUseroleid() {
		return useroleid;
	}


	public void setUseroleid(Integer useroleid) {
		this.useroleid = useroleid;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}


	public String getItemselector() {
		return itemselector;
	}


	public void setItemselector(String itemselector) {
		this.itemselector = itemselector;
	}
	

}
